﻿using System;
using System.Collections.Generic;

using System.Text;
using HZ.Data;
namespace HZ.DrugTrade.DAL
{
    public class DAL_TransformDistributionLog
    {
        public static int AddTransformDistributionLog_Batch(IList<HZ.DrugTrade.Model.TransformDistributionLog> loglist)
        {
            var sh =  HZ.Data.DbHelperFactory.Create();
            try
            {
                sh.BeginTrans();
                foreach (var item in loglist)
                {

                    string sql = HZ.Data.DAL_Helper.GetInsertSql(item);
                    sh.ExecuteNonQuery(sql);
                    //  string sql2 = string.Format("UPDATE TB_TransformDistributionLog SET IsEndNode = 0 WHERE NowCompanyID = '{0}' AND AreaID = '{1}' AND ProcureCatalogID = '{2}' AND IsEndNode = 1", item.LastCompanyID, item.AreaID, item.ProcureCatalogID);

                    // 查找当前配送是否存在
                    string sql2 = string.Format("SELECT COUNT(*) FROM TB_AreaDistribution WHERE ProcureCatalogID = '{0}' AND AreaID = '{1}' AND  CompanyID_PS = '{2}'", item.ProcureCatalogID, item.AreaID, item.NowCompanyID);
                    int count = (int)sh.ExecuteScalar(sql2);

                    if (count == 0)
                    {
                        // 不存在插入
                        HZ.DrugTrade.Model.AreaDistribution ad = new HZ.DrugTrade.Model.AreaDistribution() { AreaID = item.AreaID, ProcureCatalogID = item.ProcureCatalogID, CompanyID_PS = item.NowCompanyID, CompanyID_Main = item.LastCompanyID };
                        sh.ExecuteNonQuery(HZ.Data.DAL_Helper.GetInsertSql(ad));

                    }
                    else
                    {
                        // 存在回滚
                        sh.RollTrans();
                        return 2;
                    }

                    // 删除源配送
                    sql2 = string.Format("SELECT COUNT(*) FROM TB_AreaDistribution WHERE ProcureCatalogID = '{0}' AND AreaID = '{1}' AND  CompanyID_PS = '{2}'", item.ProcureCatalogID, item.AreaID, item.LastCompanyID);
                    count = (int)sh.ExecuteScalar(sql2);
                    if (count > 0)
                    {
                        HZ.DrugTrade.Model.AreaDistribution ad = new HZ.DrugTrade.Model.AreaDistribution() { AreaID = item.AreaID, ProcureCatalogID = item.ProcureCatalogID, CompanyID_PS = item.LastCompanyID };
                        sh.ExecuteNonQuery(HZ.Data.DAL_Helper.GetDeleteSql(ad));

                    }



                }


                sh.CommitTrans();
                return 1;
            }
            catch (Exception ee)
            {
                HZ.Common.log4netManager.LogDebug("DAL_TransformDistributionLog", ee.Message, ee);
                sh.RollTrans();
#if DEBUG
                throw ee;
#endif
                return 0;
            }

        }
    }
}
